<template>
  <McLayout class="container">
    <McHeader :title="'金融助手'" :logoImg="'https://matechat.gitcode.com/logo.svg'">
      <template #operationArea>
        <div class="operations">
          <i class="icon-finance"></i>
          <span class="operation-text">金融专家</span>
        </div>
      </template>
    </McHeader>
    <McLayoutContent
      v-if="startPage"
      style="display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px"
    >
      <McIntroduction
        :logoImg="'https://matechat.gitcode.com/logo2x.svg'"
        :title="'金融助手'"
        :subTitle="'专业金融分析与投资顾问'"
        :description="description"
      ></McIntroduction>
      <McPrompt
        :list="introPrompt.list"
        :direction="introPrompt.direction"
        class="intro-prompt"
        @itemClick="onSubmit($event.label)"
      ></McPrompt>
    </McLayoutContent>
    <McLayoutContent class="content-container" v-else>
      <!-- 金融工具面板 -->
      <FinancialTools v-if="shouldShowTools" />
      
      <!-- 对话消息 -->
      <template v-for="(msg, idx) in messages" :key="idx">
        <!-- 用户消息 -->
        <McBubble
          v-if="msg.from === 'user'"
          :content="msg.content"
          :align="'right'"
          :avatarConfig="{ imgSrc: 'https://matechat.gitcode.com/png/demo/userAvatar.svg' }"
        >
        </McBubble>
        
        <!-- 系统消息（自动追问） -->
        <McBubble 
          v-else-if="msg.from === 'system'"
          :content="msg.content"
          :avatarConfig="{ imgSrc: 'https://matechat.gitcode.com/png/demo/system.svg' }"
          :type="'system'"
        >
        </McBubble>
        
        <!-- AI回复消息 -->
        <McBubble 
          v-else 
          :content="msg.content" 
          :avatarConfig="{ imgSrc: 'https://matechat.gitcode.com/logo.svg' }" 
          :loading="msg.loading"
        >
          <template v-if="msg.qualityScore !== undefined" #footer>
            <div class="quality-indicator">
              <span class="quality-score" :class="getQualityClass(msg.qualityScore)">
                质量评分: {{ msg.qualityScore }}/100
              </span>
              <div v-if="msg.qualityFeedback && msg.qualityFeedback.length > 0" class="quality-feedback">
                <span class="feedback-label">改进建议:</span>
                <ul>
                  <li v-for="(feedback, fIdx) in msg.qualityFeedback" :key="fIdx">{{ feedback }}</li>
                </ul>
              </div>
            </div>
          </template>
        </McBubble>
      </template>
    </McLayoutContent>
    <div class="shortcut" style="display: flex; align-items: center; gap: 8px">
      <McPrompt
        v-if="!startPage"
        :list="simplePrompt"
        :direction="'horizontal'"
        style="flex: 1"
        @itemClick="onSubmit($event.label)"
      ></McPrompt>
      <Button
        style="margin-left: auto"
        icon="add"
        shape="circle"
        title="新建对话"
        size="md"
        @click="newConversation"
      />
    </div>
    <McLayoutSender>
      <McInput :value="inputValue" :maxLength="2000" @change="(e) => (inputValue = e)" @submit="onSubmit">
        <template #extra>
          <div class="input-foot-wrapper">
            <div class="input-foot-left">
              <span v-for="(item, index) in inputFootIcons" :key="index" @click="handleIconClick(item)" class="foot-icon">
                <i :class="item.icon"></i>
                {{ item.text }}
              </span>
              <span class="input-foot-dividing-line"></span>
              <span class="input-foot-maxlength">{{ inputValue.length }}/2000</span>
            </div>
            <div class="input-foot-right">
              <Button icon="op-clearup" shape="round" :disabled="!inputValue" @click="inputValue = ''"><span class="demo-button-content">清空输入</span></Button>
            </div>
          </div>
        </template>
      </McInput>
    </McLayoutSender>
  </McLayout>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { Button } from 'vue-devui/button';
import 'vue-devui/button/style.css';
import FinancialTools from './components/FinancialTools.vue';
import { 
  detectFinancialTopic, 
  generateFinancialPrompt, 
  assessAnswerQuality, 
  generateFollowUpQuestion,
  FinancialTopic 
} from './utils/financialPrompts';

const description = [
  '金融助手专注于股票分析、投资策略、风险评估、财务规划等专业领域。',
  '提供实时市场洞察、投资建议、风险评估和个性化财务规划服务。',
];

const introPrompt = {
  direction: 'horizontal',
  list: [
    {
      value: 'stockAnalysis',
      label: '分析股票投资价值',
      iconConfig: { name: 'icon-chart', color: '#5e7ce0' },
      desc: '分析特定股票的长期投资价值',
    },
    {
      value: 'investmentStrategy',
      label: '制定投资策略',
      iconConfig: { name: 'icon-strategy', color: 'rgb(255, 215, 0)' },
      desc: '根据风险偏好制定投资组合',
    },
    {
      value: 'riskAssessment',
      label: '风险评估',
      iconConfig: { name: 'icon-warning', color: '#3ac295' },
      desc: '评估投资项目的风险等级',
    },
    {
      value: 'financialPlanning',
      label: '财务规划',
      iconConfig: { name: 'icon-plan', color: '#e65c5c' },
      desc: '制定个人或企业财务规划',
    },
  ],
};

const simplePrompt = [
  {
    value: 'stockAnalysis',
    iconConfig: { name: 'icon-chart', color: '#5e7ce0' },
    label: '股票分析',
  },
  {
    value: 'investmentStrategy',
    iconConfig: { name: 'icon-strategy', color: 'rgb(255, 215, 0)' },
    label: '投资策略',
  },
  {
    value: 'marketTrend',
    iconConfig: { name: 'icon-trend', color: '#3ac295' },
    label: '市场趋势',
  },
  {
    value: 'financialPlanning',
    iconConfig: { name: 'icon-plan', color: '#e65c5c' },
    label: '财务规划',
  },
];

const startPage = ref(true);
const inputValue = ref('');
const showTools = ref(false);
const currentTopic = ref<FinancialTopic | null>(null);
const conversationContext = ref<Record<string, any>>({});

const inputFootIcons = [
  { icon: 'icon-chart', text: '股票', action: 'toggleTools' },
  { icon: 'icon-fund', text: '基金', action: 'toggleTools' },
  { icon: 'icon-bond', text: '债券', action: 'toggleTools' },
  { icon: 'icon-risk', text: '风险', action: 'toggleTools' },
];

const messages = ref<any[]>([]);

// 计算是否显示工具面板
const shouldShowTools = computed(() => {
  return showTools.value && !startPage.value;
});

const newConversation = () => {
  startPage.value = true;
  messages.value = [];
  showTools.value = false;
  currentTopic.value = null;
  conversationContext.value = {};
}

const toggleTools = () => {
  showTools.value = !showTools.value;
}

const handleIconClick = (icon: any) => {
  if (icon.action === 'toggleTools') {
    toggleTools();
  }
}

const onSubmit = async (evt) => {
  inputValue.value = '';
  startPage.value = false;
  
  // 检测金融话题
  const detectedTopic = detectFinancialTopic(evt);
  currentTopic.value = detectedTopic;
  
  // 用户发送消息
  messages.value.push({
    from: 'user',
    content: evt,
    avatarConfig: { name: 'user' },
    topic: detectedTopic
  });

  // 生成专业提示词
  let prompt = evt;
  if (detectedTopic) {
    prompt = generateFinancialPrompt(detectedTopic, conversationContext.value);
    
    // 添加上下文信息到提示词
    if (Object.keys(conversationContext.value).length > 0) {
      prompt += `\n\n对话上下文：${JSON.stringify(conversationContext.value, null, 2)}`;
    }
  }

  await fetchData(prompt, evt);
};

const fetchData = async (ques: string, originalQuestion: string) => {
  const messageIndex = messages.value.length;
  messages.value.push({
    from: 'model',
    content: '',
    avatarConfig: { name: 'model' },
    id: '',
    loading: true,
    topic: currentTopic.value
  });

  try {
    const response = await fetch('https://api.deepseek.com/v1/chat/completions', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer sk-ddeb5ddb36fe4c82bda43ca010c1daae'
      },
      body: JSON.stringify({
        model: 'deepseek-reasoner',
        messages: [{ role: 'user', content: ques }],
        stream: true
      })
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const reader = response.body?.getReader();
    if (!reader) {
      throw new Error('No reader available');
    }

    const decoder = new TextDecoder();
    let buffer = '';

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;

      buffer += decoder.decode(value, { stream: true });
      const lines = buffer.split('\n');
      buffer = lines.pop() || '';

      for (const line of lines) {
        const trimmedLine = line.trim();
        if (trimmedLine === '') continue;
        if (trimmedLine === 'data: [DONE]') break;

        if (trimmedLine.startsWith('data: ')) {
          try {
            const jsonData = JSON.parse(trimmedLine.slice(6));
            const content = jsonData.choices[0]?.delta?.content || '';
            const chatId = jsonData.id;
            
            if (content) {
              messages.value[messageIndex].content += content;
            }
            if (chatId) {
              messages.value[messageIndex].id = chatId;
            }
          } catch (e) {
            console.error('Error parsing JSON:', e);
          }
        }
      }
    }

    // 质量评估和自动追问
    if (currentTopic.value) {
      const answer = messages.value[messageIndex].content;
      const qualityAssessment = assessAnswerQuality(answer, currentTopic.value);
      
      // 记录质量评分
      messages.value[messageIndex].qualityScore = qualityAssessment.score;
      messages.value[messageIndex].qualityFeedback = qualityAssessment.feedback;
      
      // 如果需要追问，自动生成追问问题
      if (qualityAssessment.needsFollowUp && qualityAssessment.feedback.length > 0) {
        setTimeout(() => {
          const followUpQuestion = generateFollowUpQuestion(currentTopic.value!, qualityAssessment.feedback);
          messages.value.push({
            from: 'system',
            content: followUpQuestion,
            avatarConfig: { name: 'system' },
            type: 'follow-up'
          });
        }, 1000);
      }
    }

    // 更新对话上下文
    if (currentTopic.value) {
      conversationContext.value = {
        ...conversationContext.value,
        lastQuestion: originalQuestion,
        lastAnswer: messages.value[messageIndex].content,
        topic: currentTopic.value,
        timestamp: new Date().toISOString()
      };
    }

  } catch (error) {
    console.error('Error fetching data:', error);
    messages.value[messageIndex].content = '抱歉，发生了错误：' + (error as Error).message;
  } finally {
    messages.value[messageIndex].loading = false;
  }
};

// 质量评分样式分类
const getQualityClass = (score: number) => {
  if (score >= 80) return 'quality-excellent';
  if (score >= 60) return 'quality-good';
  if (score >= 40) return 'quality-fair';
  return 'quality-poor';
};
</script>

<style>
.container {
  width: 1000px;
  margin: 20px auto;
  height: calc(100vh - 82px);
  padding: 20px;
  gap: 8px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border: 1px solid #dee2e6;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.content-container {
  display: flex;
  flex-direction: column;
  gap: 8px;
  overflow: auto;
}

.operations {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #198754;
  font-weight: 600;
}

.operation-text {
  font-size: 14px;
  color: #198754;
}

.input-foot-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 100%;
  margin-right: 8px;

  .input-foot-left {
    display: flex;
    align-items: center;
    gap: 8px;

    .foot-icon {
      font-size: 14px;
      line-height: 18px;
      color: #252b3a;
      cursor: pointer;
      padding: 4px 8px;
      border-radius: 4px;
      transition: all 0.3s;
    }

    .foot-icon:hover {
      background: #f0f0f0;
      color: #1976d2;
    }

    .input-foot-dividing-line {
      width: 1px;
      height: 14px;
      background-color: #d7d8da;
    }

    .input-foot-maxlength {
      font-size: 14px;
      color: #71757f;
    }
  }

  .input-foot-right {
    .demo-button-content {
      font-size: 14px;
    }

    & > *:not(:first-child) {
      margin-left: 8px;
    }
  }
}

/* 质量评分样式 */
.quality-indicator {
  margin-top: 8px;
  padding: 8px;
  background: #f8f9fa;
  border-radius: 4px;
  border-left: 4px solid #ddd;
}

.quality-score {
  font-size: 12px;
  font-weight: 600;
  padding: 2px 6px;
  border-radius: 3px;
}

.quality-excellent {
  color: #198754;
  background: #d1e7dd;
}

.quality-good {
  color: #0d6efd;
  background: #cfe2ff;
}

.quality-fair {
  color: #ffc107;
  background: #fff3cd;
}

.quality-poor {
  color: #dc3545;
  background: #f8d7da;
}

.quality-feedback {
  margin-top: 6px;
  font-size: 11px;
}

.feedback-label {
  font-weight: 600;
  color: #6c757d;
}

.quality-feedback ul {
  margin: 4px 0 0 0;
  padding-left: 16px;
}

.quality-feedback li {
  color: #6c757d;
  line-height: 1.4;
}
</style>